<template>
  <div class="app-container home">
    <el-row :gutter="20">
      <el-col :lg="12" :sm="24" style="padding-left: 20px">
        <h4>注意事项：（推荐使用谷歌浏览器或者windows自带edge）</h4>
        <h3>如何获取cookie？</h3>
        <ul>
          <li>1、打开快手网页版，登录您的账号</li>
          <li>&nbsp;</li>
          <li>2、按下F12进入开发者模式</li>
          <li>3、找到网络并发送弹幕</li>
          <li>4、找到名称为sendComment的网络请求</li>
          <li>5、点击后找到请求标头并复制cookie</li>
        </ul>
        <h1>
          <el-button  size="small" @click="openCookie()" >
            新增cookie
          </el-button>
          <el-button  size="small" @click="open()" >
            新增直播间
          </el-button>
        </h1>
      </el-col>
      <el-col :lg="12" :sm="24" style="padding-left: 50px">
        <vue-qr :text="ksUrl" :size="200" style="display: block; margin: auto"></vue-qr>
        <li style="text-align: center">（！！）二维码需要点击用户名称后发生变化在扫</li>
      </el-col>
    </el-row>
    <el-divider/>
    <el-row :gutter="20">

      <el-col :lg="24" :sm="24">
        <el-tabs v-model="editableTabsValue" type="card" closable @tab-remove="removeTab"  @tab-click="handleClick">
          <el-tab-pane  v-for="(item, index) in editableTabs" :key="item.name" :label="item.title" :name="item.name" >
            <el-button type="success" @click="startVideo(item.name)" round>开始获取</el-button>
            <el-button type="warning" @click="stopVideo(item.name)" round>停止获取</el-button>
            <el-table
              :data="tableDataTemp"
              style="width: 100%">
              <el-table-column
                prop="roomId"
                label="房间ID"
                width="180">
              </el-table-column>
              <el-table-column
                prop="userName"
                label="用户名称"
                width="180">
                <template slot-scope="scope">
                  <p @click="goToKs(scope.row.uid)">{{scope.row.userName }}</p>
                </template>
              </el-table-column>
              <el-table-column
                prop="uid"
                label="uid"
                width="180">
                <template slot-scope="scope">
                  <p @click="goToKs(scope.row.uid)">{{ scope.row.uid }}</p>
                </template>
              </el-table-column>
              <el-table-column
                prop="type"
                label="类型"
                width="100"
                :filters="[{ text: '礼物', value: '礼物' }, { text: '弹幕', value: '弹幕' }]"
                :filter-method="filterTag"
                filter-placement="bottom-end">
                <template slot-scope="scope">
                  <el-tag
                    :type="scope.row.tag === '礼物' ? 'primary' : 'success'"
                    disable-transitions>{{scope.row.type}}</el-tag>
                </template>
              </el-table-column>

              <el-table-column
                prop="content"
                label="内容">
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>

      </el-col>
    </el-row>


  </div>
</template>

<script>
import { addVideo, startVideo, stopVideo, getStatus, sendNoindy, setCookie} from "@/api/video/ks";
import {getBlack} from "@/api/xxc/black";

import store from "@/store";
import QRCode from 'qrcodejs2'
import vueQr from 'vue-qr'

export default {
  name: "Index",
  components:{vueQr},
  data() {
    return {
      editableTabsValue: '0',
      editableTabs: [],
      tabIndex: 2,

      tableData: [],
      tableDataTemp: [],
      search: '',
      ksUrl:'',
      intervalId:null,
      ksCookie:'',

    };
  },
  created() {
    this.connectWs();
    this.fetchData(); // 创建组件时请求一次数据
    // 设置定时器每隔一分钟（60000毫秒）请求一次数据
    this.intervalId = setInterval(this.fetchData, 60000);
  },
  watch: {
    tableData(val) {
      this.tableDataTemp = this.tableData.filter(item => item.roomId === this.editableTabsValue);
    }
  },
  methods: {
    connectWs() {
      let tableData = this.tableData;
      let socket = new WebSocket(process.env.VUE_APP_BASE_API + '/ws');
      let stompClient = Stomp.over(socket);
      stompClient.connect({}, function (frame) {
        stompClient.subscribe('/sendToMessage/user/'+store.state.user.id, function (message) {
          let json = eval("(" + message.body + ")");
          tableData.unshift({
            roomId: json.roomId,
            userName: json.nickname,
            uid: json.uid,
            type: json.type,
            content: json.content
          });
        });
      });
    },
    //新建直播间
    open() {
      if(this.ksCookie == ''){
        this.$message.error('请先涉设置cookie!');
        return;
      }
      this.$prompt('请输入直播间ID', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({ value }) => {
        this.editableTabs.push({
          title: value,
          name: value
        });
        this.editableTabsValue = value;
        this.handleNewSocket(value);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
      });
    },
    openCookie() {
      this.$prompt('请输入cookie', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({ value }) => {
        this.ksCookie = value;
        let form = {};
        form.cookie = value;
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
      });
    },
    //新增直播间流
    handleNewSocket(value){
      let form = {};
      form.cookie = this.ksCookie;
      form.roomId = value;
      addVideo(form).then(response => {
        getStatus(value).then(res => {
          this.editableTabsValue = value;
          this.$message('添加成功!');

        })
      });
    },
    startVideo(name){
      startVideo(name).then(response => {
        if(response.data == 500){
          this.$confirm('请登录快手直播间，刷新处理滑块!', '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          }).then(() => {
            location.reload();
          });
        }else {
          this.$message('开启成功!');
        }
      });
    },
    stopVideo(name){
      stopVideo(name).then(response => {
        this.$message('暂停成功!');
      });
    },

    removeTab(targetName) {
      let tabs = this.editableTabs;
      let activeName = this.editableTabsValue;
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
      }

      this.editableTabsValue = activeName;
      this.editableTabs = tabs.filter(tab => tab.name !== targetName);
    },
    filterTag(value, row) {
      return row.type === value;
    },
    goToKs(uid){
        this.ksUrl = "https://live.kuaishou.com/profile/"+uid;
    },
    handleClick(tab,enet){
      let name = this.editableTabs[tab.index].name;
      this.editableTabsValue = name;
      this.tableDataTemp = [];
      this.tableDataTemp = this.tableData.filter(item => item.roomId === name);
    },
    fetchData() {
      sendNoindy().then(res => {
       console.log("开始轮询")

      })
    },
    beforeDestroy() {
      // 清除定时器
      if (this.intervalId) {
        clearInterval(this.intervalId);
      }
    },

  }
}
</script>

<style lang="scss" scoped>
.home {
  blockquote {
    padding: 10px 20px;
    margin: 0 0 20px;
    font-size: 17.5px;
    border-left: 5px solid #eee;
  }

  hr {
    margin-top: 20px;
    margin-bottom: 20px;
    border: 0;
    border-top: 1px solid #eee;
  }

  .col-item {
    margin-bottom: 20px;
  }

  ul {
    padding: 0;
    margin: 0;
  }

  font-family: "open sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 13px;
  color: #676a6c;
  overflow-x: hidden;

  ul {
    list-style-type: none;
  }

  h4 {
    margin-top: 0px;
  }

  h2 {
    margin-top: 10px;
    font-size: 26px;
    font-weight: 100;
  }

  p {
    margin-top: 10px;

    b {
      font-weight: 700;
    }
  }

  .update-log {
    ol {
      display: block;
      list-style-type: decimal;
      margin-block-start: 1em;
      margin-block-end: 1em;
      margin-inline-start: 0;
      margin-inline-end: 0;
      padding-inline-start: 40px;
    }
  }
}
</style>

